<template>
  <Dialog width="800px" :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="150px"
      v-loading="formLoading"
    >
      <el-form-item label="语句⽂本" prop="content">
        <el-input v-model="formData.content" placeholder="请输入语句" />
      </el-form-item>
      <el-form-item label="标签" prop="tagIdArray">
        <el-select filterable multiple v-model="formData.tagList" placeholder="请输入标签id数组，一个音频可以有多个标签">
          <el-option v-for="item in tagList" :key="item.id" :value="item.id" :label="item.tagName" />
        </el-select>
      </el-form-item>
      <el-form-item label="关键字" prop="keyworldList">
        <el-select filterable multiple v-model="formData.keyworldList" placeholder="请输入关键字">
          <el-option v-for="item in keywordList" :key="item.id" :value="item.id" :label="item.keyWord" />
        </el-select>
      </el-form-item>
      <el-form-item  label="关联类型" prop="relationType">
        <el-select v-model="formData.relationType" placeholder="1，默认，2，回复类型">
          <el-option :value="EnumRelationType.DEFAULT" label="默认" />
          <el-option :value="EnumRelationType.RESPONSE" label="回复类型" />
        </el-select>
      </el-form-item>
      <el-form-item v-if="formData.relationType == EnumRelationType.RESPONSE" label="关联内容" prop="audioTextRelationList">
        <el-button @click="addAudioRelation" type="primary">+</el-button>
        <ul style="width:100%;" class="audio-relation-ul">
          <li :key="item.id" v-for="item in formData.audioTextRelationList">
            <div >
              <span class="field-tag">是否默认：</span>
              <el-select style="width:200px;" v-model="item.defaultCon" placeholder="是否默认回复">
                <el-option :value="1" label="是" />
                <el-option :value="0" label="否" />
              </el-select>
            </div>
            <!--选择关键字-->
            <div v-if="!item.defaultCon">
              <span class="field-tag">关键字：</span>
              <el-button style="margin-right:12px;" size="small" @click="showKeyWordChooser(item)" type="primary">+</el-button>
              <span >{{item.keywordList ? item.keywordList.map(e=>e.keyWord).join("、") : ''}}</span>
            </div>
            <!--选择音频-->
            <div >
              <span class="field-tag">关联语句⽂本：</span>
              <el-input style="width:400px;" v-model="item.relationText" />
            </div>
            <el-button title="删除" @click="removeAudioRelation(item)" size="small" type="info" class="delete-btn">-</el-button>
          </li>
        </ul>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <KeywordChooser @submit="submitKeyword" ref="keywordChooserRef" />
</template>
<script setup lang="ts">
import { AudioTextApi } from '@/api/lm/audiotext'
import KeywordChooser from '@/views/audio/components/KeywordChooser.vue';

/** 音频 表单 */
defineOptions({ name: 'AudioForm' })
const EnumRelationType = {
  DEFAULT: 1,
  RESPONSE: 2
};
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const keywordChooserRef = ref();
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const tagList = ref([]) // 标签列表
const keywordList = ref([]) // 关键字列表
const curOperateRelationItem = ref({});
const formData = ref({
  id: undefined,
  content: undefined,
  relationType: EnumRelationType.DEFAULT,
  audioTextRelationList: [],
  tagList: undefined,
  keyworldList: undefined,
})
const formRules = reactive({
  content: [{ required: true, message: '文本不能为空', trigger: 'blur' }],
  relationType: [{ required: true, message: '请选择关联类型', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

watch(()=>formData.value.relationType, ()=> {
  if(formData.value.relationType == EnumRelationType.DEFAULT) {
    formData.value.audioTextRelationList = [];
  }
})

/** 打开弹窗 */
const open = async (type: string, id?: number, options?:any) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  tagList.value = options.tagList;
  keywordList.value = options.keywordList;
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      let resData = await AudioTextApi.getAudioText(id);
      resData.tagList = resData.tagList?.map(e=> {
        return e.id;
      });
      resData.keyworldList = resData.keyworldList?.map(e=> {
        return e.id;
      });
      if(!resData.audioRelationRespVoList) {
        resData.audioRelationRespVoList = [];
      }
      // 提取数据
      resData.audioTextRelationList.forEach((item,index) =>{
        item.keywordList = item.keyWordRespVOList || [];
        item.keywordIds = item.keywordIds || [];
        item.id = +new Date() + index;
        item.defaultCon = +item.defaultCon;
      });
      if(!resData.relationType) {
        resData.relationType = EnumRelationType.DEFAULT;
      }
      formData.value = resData;
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  if (formData.value.relationType == EnumRelationType.RESPONSE && !formData.value.audioTextRelationList.length) {
    return message.warning("关联内容未设置，请检查")
  }
  if (formData.value.audioTextRelationList.filter(e => !e.relationText).length > 0) {
    return message.warning("音频关联内容里有文本没有关联，请设置")
  }

  // 提交请求
  formLoading.value = true
  try {
    const data = {
      ...formData.value
    } as unknown as AudioVO
    data.audioTextRelationList.forEach(item=> {
      item.defaultCon = !!item.defaultCon;
    });
    if (formType.value === 'create') {
      await AudioTextApi.createAudioText(data)
      message.success(t('common.createSuccess'))
    } else {
      await AudioTextApi.updateAudioText(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

function addAudioRelation() {
  formData.value.audioTextRelationList.push({
    id: +new Date(),
    defaultCon: 0,
    keywordIds: [],
    relationText: "",
    keywordList: []
  })
}

function showKeyWordChooser(item) {
  curOperateRelationItem.value = item;
  keywordChooserRef.value.open({
    chooseList: item.keywordList|| []
  });
}

function removeAudioRelation(item) {
  const index = formData.value.audioTextRelationList.findIndex(e=> e.id === item.id);
  if (index !== -1) {
    formData.value.audioTextRelationList.splice(index, 1);
  }
}

function submitKeyword(list) {
  curOperateRelationItem.value.keywordList = list;
  curOperateRelationItem.value.keywordIds = list.map(e=> {
    return e.id;
  });
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    content: undefined,
    tagList: undefined,
    keyWordIdArray: undefined,
    relationType: EnumRelationType.DEFAULT,
    audioTextRelationList: []
  }
  formRef.value?.resetFields()
}

</script>

<style lang="scss" scoped>
.field-tag {
  display: inline-block;
  width: 120px;
}
.audio-relation-ul {
  list-style: none;
  padding: 0px;
  border-top: 1px solid #D5D5D5;
  li {
    border-bottom: 1px solid #D5D5D5;
    padding: 12px 0px;
    position: relative;
    .delete-btn {
      position: absolute;
      right: 0px;
      top: 12px;
    }
  }
}
</style>
